package impl

import (
	"adam2/internal/domain"
	"adam2/internal/model"
	"anubis-framework/pkg/io"
)

type QuantAccountLogDaoImpl struct {
	*BaseDaoImpl
}

// 返回dao实现类
func GetQuantAccountLogDaoImpl() *QuantAccountLogDaoImpl {
	return &QuantAccountLogDaoImpl{GetBaseDaoImpl()}
}

// 返回表名
func (_quantAccountLogDaoImpl *QuantAccountLogDaoImpl) FindTableName() string {
	return "QUANT_ACCOUNT_LOG"
}

// 根据开始时间、结束时间查询记录，并按照date_和account_name列升序排列
func (_quantAccountLogDaoImpl *QuantAccountLogDaoImpl) FindByBeginDateAndEndDateOrderByDateAndAccountName(beginDate string, endDate string) model.QuantAccountLogArray {
	io.Infoln("根据开始时间、结束时间查询记录，并按照date_和account_name列升序排列")

	// 查询记录
	var quantAccountLogArray *model.QuantAccountLogArray = &model.QuantAccountLogArray{}
	_quantAccountLogDaoImpl.db.Raw("select * from quant_account_log t "+
		"where t.date_ between to_date(?,'yyyy-mm-dd') and to_date(?,'yyyy-mm-dd') "+
		"order by t.date_ asc, t.account_name asc", beginDate, endDate).Scan(quantAccountLogArray)

	return *quantAccountLogArray
}

// 根据开始时间、结束时间、account_name查询记录，并按照date_和account_name列升序排列
func (_quantAccountLogDaoImpl *QuantAccountLogDaoImpl) FindByBeginDateAndEndDateAndAccountNameOrderByDateAndAccountName(beginDate string, endDate string, accountName string) model.QuantAccountLogArray {
	io.Infoln("根据开始时间、结束时间、account_name查询记录，并按照date_和account_name列升序排列")

	// 查询记录
	var quantAccountLogArray *model.QuantAccountLogArray = &model.QuantAccountLogArray{}
	_quantAccountLogDaoImpl.db.Raw("select * from quant_account_log t "+
		"where t.date_ between to_date(?,'yyyy-mm-dd') and to_date(?,'yyyy-mm-dd') and t.account_name=? "+
		"order by t.date_ asc, t.account_name asc", beginDate, endDate, accountName).Scan(quantAccountLogArray)

	return *quantAccountLogArray
}

// 计算最大回撤
func (_quantAccountLogDaoImpl *QuantAccountLogDaoImpl) CalculateMaximumDrawdown() domain.MaximumDrawdownArray {
	io.Infoln("计算最大回撤")

	var maximumDrwadownArray domain.MaximumDrawdownArray
	_quantAccountLogDaoImpl.db.Raw("select * from (" +
		"select (t1.total_assets-t2.total_assets)/t1.total_assets*100 MAXIMUM_DRAWDOWN, " +
		"t1.date_ DATE1, t2.date_ DATE2, t1.account_name ACCOUNT_NAME, t1.total_assets TOTAL_ASSETS1, " +
		"t2.total_assets TOTAL_ASSETS2 " +
		"from quant_account_log t1, quant_account_log t2 " +
		"where t1.account_name=t2.account_name and t1.date_<t2.date_ " +
		"order by (t1.total_assets-t2.total_assets)/t1.total_assets*100 desc) " +
		"where rownum<=10").Scan(&maximumDrwadownArray)

	return maximumDrwadownArray
}

// 根据日期删除记录
func (_quantAccountLogDaoImpl *QuantAccountLogDaoImpl) DeleteByDate(date string) {
	io.Infoln("根据日期[%s]删除记录", date)

	_quantAccountLogDaoImpl.db.Exec("delete from quant_account_log t where t.date_=to_date(?,'yyyy-mm-dd')", date)
}